﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Niknak.Services.ServiceCore.TaskScheduler;
using System.Threading;

namespace Sandbox
{
    public class TestTask : AdvancedTaskProcessor<TaskConfig4>
    {
        private static bool _TerminationRequested = false;

        public override void Initialise()
        {
            _TaskProcessor = ProcessIteration;
            base.IterationStarting += new EventHandler<IterationEventArgs>(TestTask_IterationStarting);
            base.IterationTerminationRequest += new EventHandler<IterationEventArgs>(TestTask_IterationTerminationRequest);
            base.IterationCompleted += new EventHandler<IterationEventArgs>(TestTask_IterationCompleted);
            base.Initialise();
        }

        void TestTask_IterationStarting(object sender, IterationEventArgs e)
        {
            Console.WriteLine("Iteration (" + e.IterationDate.ToString() + ") started...");
        }

        void TestTask_IterationTerminationRequest(object sender, IterationEventArgs e)
        {
            Console.WriteLine("Iteration (" + e.IterationDate.ToString() + ") termination requested");
            _TerminationRequested = true;
        }

        void TestTask_IterationCompleted(object sender, IterationEventArgs e)
        {
            Console.WriteLine("Iteration (" + e.IterationDate.ToString() + ") completed");
        }

        private static void ProcessIteration(object obj)
        {
            if (!(obj is TaskConfig4))
                throw new Exception("Settings object passed to ProcessIteration was not of type TaskConfig4");

            TaskConfig4 config = (TaskConfig4)obj;

            Console.WriteLine(DateTime.UtcNow.ToString() + ": Task was run!");
            Console.WriteLine("Sleeping...");

            while (!_TerminationRequested)
            {
                Thread.Sleep(1000);
            }

            Console.WriteLine("Done sleeping");
        }
    }
}
